from django.db import models
from django.utils.translation import ugettext_lazy as _
from mbserver.source.parser import *

class Parser(models.Model):

    LANGUAGES = (
        ('xslt', 'XSLT'),
        ('regexp', 'Regular Expression'),
        ('rss', 'RSS'),
    )

    name = models.CharField(_('Name'), help_text=_('Name of parser'), max_length=250)
    description = models.TextField(_('Description'), help_text=_('Parser description and documentation'), max_length=1024, blank=True)
    type = models.CharField(_('Type'), help_text=_('Parser Type'), max_length=250, choices=LANGUAGES, default='xslt')
    file = models.FileField(_('File'), help_text=_('Parser file'), upload_to = 'parser/%Y/%M', blank=True, null=True)
    regexp_title = models.CharField(_('Title RegExp'), max_length=2048, blank=True, null=True)
    regexp_description = models.CharField(_('Description RegExp'), max_length=2048, blank=True, null=True)
    regexp_link = models.CharField(_('Link RegExp'), max_length=2048, blank=True, null=True)

    def __unicode__(self):
        return self.name

    def get_parser(self):
        if self.type == 'xslt':
            return XsltParser(self)
        elif self.type == 'regexp':
            return RegExpParser(self)
        elif self.type == 'rss':
            return RssParser(self)
        else:
            return None 

    class Meta:
        verbose_name = _('Parser')
        verbose_name_plural = _('Parsers')

class Group(models.Model):
    name = models.CharField(_('Name'), help_text=_('Group name'), max_length=250)
    parent = models.ForeignKey('self', help_text=_('Parent group'), null=True, blank=True)

    def __unicode__(self):
        return self.name

    class Meta:
        verbose_name = _('Group')
        verbose_name_plural = _('Groups')

class Source(models.Model):

    name = models.CharField(_('Name'), help_text=_('Name of search engine'), max_length=250)
    url = models.CharField(_('Search URL'), help_text=_('URL of search engine'), unique=True, max_length=250)
    is_rss = models.BooleanField(_('Is RSS'), help_text=_('Mark it if the search engine return RSS data'), default=True)
    op_and = models.CharField(_('AND'), help_text=_('AND operator string to this search'), max_length=250, default='AND')
    op_or = models.CharField(_('OR'), help_text=_('OR operator string to this search'), max_length=250, default='OR')
    cache_expires = models.IntegerField(_('Cache expires'), help_text=_('Seconds time to exipires cache results'), default=60*60*24) # Default one day
    parser = models.ForeignKey(Parser, help_text=_('Parser file to transform the response in RSS'))
    group = models.ManyToManyField(Group, help_text=_('Group of this source'), null=True, blank=True)

    def __unicode__(self):
        return self.name

    class Meta:
        verbose_name = _('Source')
        verbose_name_plural = _('Sources')
